package spark.streaming

import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * @Author Jeremy Zheng
 * @Date 2021/6/12 13:04
 * @Version 1.0
 */
object SparkStreaming01_WordCount {
  def main(args: Array[String]): Unit = {
    //创建环境对象
    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("SparkStreaming")
    //第二个参数是表示批量处理的周期（采集周期）
    val ssc = new StreamingContext(sparkConf,Seconds(3))

    //逻辑处理
    val lines: ReceiverInputDStream[String] = ssc.socketTextStream("localhost", 9999)
    val words: DStream[String] = lines.flatMap(_.split(" "))
    val wordToOne: DStream[(String, Int)] = words.map((_, 1))
    val wordTOCount: DStream[(String, Int)] = wordToOne.reduceByKey(_ + _)
    wordTOCount.print()

    //关闭环境对象
    //由于SparkStreaming的采集器是长期执行的任务，所以不能直接关闭
    //main方法执行完毕应用程序也会自动结束，所以不能让main执行完毕
    //1.启动采集器
    ssc.start()
    //2.等待采集器关闭
    ssc.awaitTermination()
  }
}
